<template>
  <div class="update-main">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="updateForm"
    >
      <el-form-item label="新密码" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="确认新密码" prop="checkPass">
        <el-input
            v-model="ruleForm.checkPass"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">
          提交
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";
import {updatePsw} from "@/api/healthApi.js";
import router from "@/router/index.js";

export default {
  name: "UpdatePsw",
  data() {
    return {
      //表单
      ruleForm: {
        pass: '',
        checkPass: '',
      },
      //规则
      rules: {
        pass: [{validator: this.validatePass, trigger: 'blur'}],
        checkPass: [{validator: this.validatePass2, trigger: 'blur'}],
      },
    }
  },
  created() {

  },
  methods: {
    //验证1
    validatePass(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    },
    //验证2
    validatePass2(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再输入一遍密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两个密码不一致"))
      } else {
        callback()
      }
    },
    submitForm() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          updatePsw(this.ruleForm.pass).then(res => {
            ElMessage({message: res.msg, type: 'success'})
            router.push({name: 'MyArticles'})
          })
        } else {
          console.log('error submit!')
        }
      })
    },
    //重置
    resetForm() {
      this.ruleForm = {}
    }
  },
}
</script>
<style scoped>
.update-main {
  width: 100%;
  height: 100vh;
}

.updateForm {
  position: relative;
  width: 30%;
  left: 30%;
  top: 20%;
}
</style>